package com.itshen.service.impl;

import com.itshen.client.ItemClient;
import com.itshen.client.OrderClient;
import com.itshen.domain.dto.OrderDTO;
import com.itshen.domain.entity.Item;
import com.itshen.mapper.OrderMapper;
import com.itshen.result.Result;
import com.itshen.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ItemClient client;

    @Override
    @Transactional
    public Result<String> place( OrderDTO orderDTO) {
        //获取商品的种类，并在item模块中扣除相应的商品数量
        List<Item> items = orderDTO.getItems();
        Map<Long, Integer> itemId_Num = items.stream().collect(Collectors.toMap(Item::getId, Item::getStock));
        //扣减库存
        client.deductInventory(itemId_Num);

        //将订单保存到数据库中
        int flag=orderMapper.insert(orderDTO.getOrderId(),orderDTO.getUserId(),orderDTO.getTotalAmount(),orderDTO.getStatus());
        if(flag==1){
            return Result.success("下单成功");
        }
        return Result.error("下单失败");
    }
}
